﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using Newtonsoft.Json;
using System.Net;
using System.IO;
using UcAsp.Net.Model;
using UcAsp.Net.BLL;
using System.Web;
namespace UcAsp.Net.OpenApi.Weibo
{
    public  class Api:BaseOpenApi
    {
        public override string Login()
        {
            return "https://api.weibo.com/oauth2/authorize?client_id=" + ConfigurationManager.AppSettings["WAPPID"] + "&response_type=code&redirect_uri=" + ConfigurationManager.AppSettings["WRedirect"] + "";
        }
        public override bool OpenApi(string Code)
        {
            try
            {
                Dictionary<string, string> param = new Dictionary<string, string>();
                param.Add("client_id", BLL.SysParamBLL.GetParamByName("WAPPID"));
                param.Add("client_secret", BLL.SysParamBLL.GetParamByName("WAPPKEY"));
                param.Add("grant_type", BLL.SysParamBLL.GetParamByName("GrantType"));
                param.Add("redirect_uri", BLL.SysParamBLL.GetParamByName("WRedirect"));
                param.Add("code", Code);
                string token = HttpWebClient.PostString("https://api.weibo.com/oauth2/access_token", param);
                JsonReader json = new JsonTextReader(new StringReader(token));
                JsonSerializer serializer = new JsonSerializer();
                WeiboToken weibo = (WeiboToken)serializer.Deserialize(json, typeof(WeiboToken));
                string userinfo = HttpWebClient.GetString("https://api.weibo.com/2/users/show.json?access_token=" + weibo.access_token + "&uid=" + weibo.uid);
                JsonReader userjson = new JsonTextReader(new StringReader(userinfo));
                WeiboUser weibouser = (WeiboUser)serializer.Deserialize(userjson, typeof(WeiboUser));
                this.NickName = weibo.uid;
                //if (weibouser != null)
                //{

                    UserInfo user = new BLL.UserInfoBLL().GetUserInfoByNameAndOpenID(weibouser.name, BLL.SysParamBLL.GetParamByName("WAPPID"));
                    if (user == null)
                    {
                        int recommandid = 0;
                        if (HttpContext.Current.Request.Cookies["User"] != null)
                        {
                            recommandid = int.Parse(HttpContext.Current.Request.Cookies["User"]["UserID"].ToString());
                            UserInfo recomuser = new UserInfoBLL().GetUserInfoByID(recommandid);
                            recomuser.Point += int.Parse(SysParamBLL.GetParamByName("RecommendPoint"));
                            new BLL.UserInfoBLL().Update(recomuser);
                        }
                        user = new UserInfo { UserName = weibouser.name, SessionID = weibo.access_token, OpenID = weibo.uid, Point = int.Parse(SysParamBLL.GetParamByName("Point")), LoginTime = DateTime.Now, Logo = weibouser.profile_image_url, LoginIP = HttpContext.Current.Request.UserHostAddress, Remark = weibouser.remark, RecommendID=recommandid, };
                        new BLL.UserInfoBLL().Insert(user);
                    }
                    else
                    {
                        TimeSpan ts = DateTime.Now - user.LoginTime;
                        double timespan = Math.Abs(ts.TotalDays);
                        if (timespan > 1)
                        {
                            user.Point += int.Parse(SysParamBLL.GetParamByName("PrePoint"));
                            
                        }
                        user.SessionID = weibo.access_token;
                        user.LoginTime = DateTime.Now;
                        new BLL.UserInfoBLL().Update(user);
                    }
                    HttpContext.Current.Session["UserID"] = user.ID;
                    return true;
            //    }
            //    else
            //    {
            //        return false;
            //    }


            }
            catch
            {
                return false;
            }
        }
        public override bool WriteWeibo(string content,string urlfile,string access_token)
        {
            content = content.Length > 140 ? content.Substring(0, 140) : content;
            Dictionary<object, object> param = new Dictionary<object, object>();
            param.Add("status", Uri.EscapeDataString(content));
            param.Add("access_token", access_token);
            
            byte[] pic = new WebClient().DownloadData(urlfile);
            HttpWebClient.HttpPost("https://upload.api.weibo.com/2/statuses/upload.json", param, pic);
            return true;
        }
        public override bool AddFollow(string usernick,string access_token)
        {
            Dictionary<string, string> param = new Dictionary<string, string>();
            param.Add("uid", BLL.SysParamBLL.GetParamByName("WeiboUid"));
            param.Add("access_token", access_token);
             HttpWebClient.PostString("https://api.weibo.com/2/friendships/create.json", param);
             return true;
            
        }
    }
}
